//
//  OAuthViewController.swift
//  Weibo
//
//  Created by 5201-mac on 2017/4/16.
//  Copyright © 2017年 wlb-mac. All rights reserved.
//

import UIKit

class OAuthViewController: UIViewController, UIWebViewDelegate {

    lazy var webView = UIWebView()
    
    override func loadView() {
        //1.实例化一个webView（加载网页的控件）对象，作为根视图控制器
        view = webView
        //设置代理对象为当前视图控制器
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        loadOAuthPage()
        
    }
    
    func setupUI() {
        self.view.backgroundColor = UIColor.white
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(OAuthViewController.close))
    }
    
    //加载授权页面
    func loadOAuthPage() {
        
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        //实例化url对象
        let url = NSURL(string: urlString)
        //实例化request对象
        let req = NSURLRequest(url: url! as URL)
        //通过webView加载一个网页页面
        webView.loadRequest(req as URLRequest)
    }
    
    //关闭当前页面
    func close() {
        self.dismiss(animated: true, completion: nil)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    //加载新的页面需要使用等待指示器
    func webViewDidStartLoad(_ webView: UIWebView) {
        //开启用户等待指示器
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        //消失用户等待指示器
        SVProgressHUD.dismiss()
    }
    
    //返回值为bool类型的协议方法，通常情况下返回false，提供协议的对象就不能正常工作
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //每次加载新的页面都会将request对象回调回来
        //print(request.url?.absoluteString)
        let urlString = request.url?.absoluteString ?? ""
        let flag = "code="
        if urlString.contains(flag) {
            //代表用户授权成功
            //开启截取code
            let query = request.url?.query ?? ""
            print(query)
            let code = query.substring(from: flag.endIndex)
            print(code)
            //使用code来获取授权过后的token（令牌）
            loadAccessToken(code: code)
            //如果授权成功就不要加载回调页面
            return false
        }
        return true
    }
    
    //通过POST请求提交一系列参数，获取授权过后的token
    func loadAccessToken(code: String) {
        //做POST请求
        //1.实例化AFN对象
        let urlString = "https://api.weibo.com/oauth2/access_token"
        //实例化参数
        let dict = ["client_id" : client_id, "client_secret" : client_scrcet, "grant_type" : "authorization_code", "code" : code, "redirect_uri" : redirect_uri]
        let AFN = AFHTTPSessionManager()
        //设置AFN反序列化支持 text/plain格式的数据
        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
        //2.调用POST请求的方法
        AFN.post(urlString, parameters: dict, progress: nil, success: { (_, responseObject) in
            //成功的回调
            //print(responseObject)
            //将token缓存到本地
            //字典转模型
            let userAccount = UserAccount(dict: responseObject as! [String: NSObject])
            print(userAccount)
            //通过归档来保存自定义对象到磁盘和解归档将磁盘中的二进制数据解归档成自定义对象的方法来
            userAccount.saveAccount()
            
            //获取自定义对象
//            let cacheAccount = UserAccount.loadAccount()
//            print(cacheAccount)
            //登录成功之后，就应该重新加载根视图控制器MainViewController
            UIApplication.shared.keyWindow?.rootViewController = MainViewController()
        }) { (_, error) in
            //失败的回调
            print(error)
        }
    }

}
